package com.qiangqiang.dbpool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by q on 2018/3/28.
 */
public class ConPool {
    private List<MyCon> freeCons = new ArrayList<MyCon>();
    private List<MyCon> buzyCons = new ArrayList<MyCon>();
    private int max = 10;
    private int min = 2;
    private int current = 0;

    /**
     * 单例实例
     **/
    private volatile static ConPool instance;

    private ConPool() {
        while (this.min > this.current) {
            this.freeCons.add(this.createCon());
        }
    }

    /**
     * 获取池实例
     *
     * @return
     */
    public static ConPool getInstance() {
        if (instance == null) {
            synchronized (ConPool.class) {
                if (instance == null) {
                    instance = new ConPool();
                }
            }
        }
        return instance;
    }

    /**
     * 获取空闲数据库连接
     * 先从空闲列表中找出一个连接
     * 如果空闲链表中没有连接，则试图创建一个连接
     *
     * @return
     */
    public MyCon getCon() {
        MyCon myCon = this.getFreeCon();
        if (myCon != null) {
            return myCon;
        } else {
            return this.getNewCon();
        }
    }

    private MyCon createCon() {
        try {
            Connection con = MySqlDAO.getConnection();
            MyCon myCon = new MyCon(con);
            this.current++;
            return myCon;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public MyCon getFreeCon() {
        if (freeCons.size() > 0) {
            MyCon con = freeCons.remove(0);
            con.setState(MyCon.BUZY);
            this.buzyCons.add(con);
            return con;
        } else {
            return null;
        }
    }

    public MyCon getNewCon() {
        if (this.current < this.max) {
            MyCon myCon = this.createCon();
            myCon.setState(MyCon.BUZY);
            this.buzyCons.add(myCon);
            return myCon;
        } else {
            return null;
        }
    }

    /**
     * 将连接设为空闲状态
     */
    public void setFree(MyCon con) {
        this.buzyCons.remove(con);
        con.setState(MyCon.FREE);
        this.freeCons.add(con);
    }

    public String toString() {
        return "当前连接数：" + this.current + "空闲连接数：" + this.freeCons.size() +
                "繁忙连接数：" + this.buzyCons.size();
    }
}
